import React from "react";
import { Toast, Modal } from "antd-mobile";
import wx from "weixin-js-sdk";
const prompt = Modal.prompt;

export default class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      flower: 0,
      rmb: 0,
      sign: null, //是否签到
      share: null, //是否已分享
      dianzan: 0, //点赞次数
      crystal: 0,
      sign_num: 0,
      share_num: 0,
      dianzan_num: 0,
      card_end: 0,
      day: 0,
      hour: 0,
      minute: 0,
      second: 0,
      is_quan: 0,
    };
  }
  componentWillUnmount() {
    if (this.timer) {
      clearInterval(this.timer);
    }
   
  }
  componentDidMount() {
    document.title = "我的";
    global.Ajax.hhtc_request("user/get_qrcode", {}).then((data) => {
      console.log("第一步 ", data);
      if (data.code === 1) {
        this.setState(data.data);
      }
    });

    global.Ajax.hhtc_request("web/get_share", {
      windowurl: window.location.href,
    }).then((data) => {
      console.log("分享页面的数据 ", data);
      if (data.code === 1) {
        wx.config({
          debug: false,
          appId: data.data.appId,
          timestamp: data.data.timestamp,
          nonceStr: data.data.noncestr,
          signature: data.data.signature,
          jsApiList: [
            // 所有要调用的 API 都要加到这个列表中
            "updateTimelineShareData", //分享给好友
            "updateAppMessageShareData", //分享到朋友圈
          ],
        });

        wx.checkJsApi({
          jsApiList: ["updateTimelineShareData", "updateAppMessageShareData"], // 需要检测的JS接口列表，所有JS接口列表见附录2,
          success: function (res) {
            console.log("checkJsApi--", res);
            // 以键值对的形式返回，可用的api值true，不可用为false
            // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
          },
        });
        wx.error(function (res) {
          console.log(res);
          // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        });

        wx.ready(() => {
          //配置好需要分享的几个配置，这里只是演示，实际开发中应该是动态的变量
          var shareData = {
            title: "好友邀请你加入艺看学院",
            desc: "你的好友正在邀请你加入艺看学院，快来看看吧",
            link: window.location.href.split("#")[0],
            imgUrl:
              "https://yksy.qianjitianxia.com/o_1eiao12gcfa6122j1eicun0pjl8.png", //传递给微信需传递完整的带url链接
            success: function () {
              global.Ajax.hhtc_request("user/share", {}).then((data) => {
                console.log("data: ", data);
                // return Toast.success(data.msg);
              });
            },
          };

          //调用各个接口并传入配置变量
          wx.updateTimelineShareData(shareData);
          wx.updateAppMessageShareData(shareData);
        });
      }
    });
    this.getInfo();
    let me = this;
    setTimeout(() => {
      const end = Date.parse(new Date(me.state.card_end));
      this.countFun(end);

      console.log("me.state.card_end: ", me.state.card_end);
    }, 1000);

  }

  getInfo() {
    global.Ajax.hhtc_request("user/userinfo", {}).then((data) => {
      console.log("data: ", data);
      if (data.code === 1) {
        this.setState(data.data);
      }
    });
  }
  // 签到
  sign() {
    global.Ajax.hhtc_request("user/sign", {}).then((data) => {
      console.log("data: ", data);
      Toast.info(data.msg, 1, () => {
        this.getInfo();
      });
    });
  }
  // 积分兑
  duih() {
    prompt(
      <p>
        <img
          alt=''
          src={require("../../imgs/hua.png")}
          style={{ display: "block", width: "9.334vw", margin: "0 auto" }}
        />
      </p>,
      "",
      [
        {
          text: "取消",
          onPress: (value) =>
            new Promise((resolve) => {
              resolve();
            }),
        },
        {
          text: "兑换",
          onPress: (value) =>
            new Promise((resolve, reject) => {
              if (value * 1 + "" === "NaN") {
                return Toast.fail("只能输入数字噢!", 1);
              }
              if (value !== "") {
                global.Ajax.hhtc_request("user/dh_flower", { num: value }).then(
                  (data) => {
                    if (data.code === 1) {
                      Toast.success(data.msg, 1, () => {
                        this.getInfo();
                      });
                      resolve();
                    } else {
                      Toast.fail(data.msg, 1);
                    }
                  }
                );
              } else {
                Toast.fail("请输入数量");
              }
            }),
        },
      ],
      "default",
      null,
      ["请输入要兑换的数量"]
    );
  }
  // 水晶兑换
  shuijin() {
    prompt(
      <p>
        <img
          alt=''
          src={require("../../imgs/999.png")}
          style={{ display: "block", width: "9.334vw", margin: "0 auto" }}
        />
      </p>,
      "",
      [
        {
          text: "取消",
          onPress: (value) =>
            new Promise((resolve) => {
              resolve();
            }),
        },
        {
          text: "兑换",
          onPress: (value) =>
            new Promise((resolve, reject) => {
              if (value * 1 + "" === "NaN") {
                return Toast.fail("只能输入数字噢!", 1);
              }
              if (value !== "") {
                global.Ajax.hhtc_request("user/crystal", {
                  number: value,
                }).then((data) => {
                  if (data.code === 1) {
                    Toast.success(data.msg, 1, () => {
                      this.getInfo();
                    });
                    resolve();
                  } else {
                    Toast.fail(data.msg, 1);
                  }
                });
              } else {
                Toast.fail("请输入数量");
              }
            }),
        },
      ],
      "default",
      null,
      ["请输入要兑换的数量"]
    );
  }

  //
  countFun = (end) => {
    let now_time = Date.parse(new Date());
    console.log("now_time: ", now_time);
    var remaining = end - now_time;
    console.log("remaining: ", remaining);

    this.timer = setInterval(() => {
      //防止出现负数
      if (remaining > 1000) {
        remaining -= 1000;
        let day = Math.floor(remaining / 1000 / 3600 / 24);
        let hour = Math.floor((remaining / 1000 / 3600) % 24);
        let minute = Math.floor((remaining / 1000 / 60) % 60);
        let second = Math.floor((remaining / 1000) % 60);

        this.setState({
          day: day,
          hour: hour < 10 ? "0" + hour : hour,
          minute: minute < 10 ? "0" + minute : minute,
          second: second < 10 ? "0" + second : second,
        });
      } else {
        clearInterval(this.timer);
        //倒计时结束时触发父组件的方法
        //this.props.timeEnd();
      }
    }, 1000);
  };

  render() {
    return (
      <div className='' style={{ paddingBottom: 60 }}>
        <img
          alt=''
          src={require("../../imgs/set.png")}
          className='set'
          onClick={() => {
            this.props.history.push("/page/home/user/set");
          }}
        />
        <div className='user_info'>
          <img alt='' src={this.state.avatar} className='head' />
          <div className='right'>
            <p className='name'>{this.state.nickname}</p>
            {this.state.level === 1 && (
              <img
                alt=''
                src={require("../../imgs/vip1.png")}
                className='vip'
              />
            )}
            {this.state.level === 2 && (
              <img
                alt=''
                src={require("../../imgs/vip2.png")}
                className='vip'
              />
            )}
            {this.state.level === 3 && (
              <img
                alt=''
                src={require("../../imgs/nfei.png")}
                className='vip'
                style={{ width: 27 }}
              />
            )}
          </div>
        </div>
        <div className='user_menu'>
          <div>
            <h1>{this.state.flower * 1}</h1>
            <p>鲜花</p>
          </div>
          <div onClick={this.shuijin.bind(this)}>
            <h1>{this.state.crystal * 1}</h1>
            <p>水晶</p>
          </div>
          <div onClick={this.duih.bind(this)}>
            <h1>{this.state.rmb * 1}</h1>
            <p>积分</p>
          </div>
          <div
            onClick={() => {
              this.props.history.push(
                "/page/home/user/withdrawal/" + this.state.bl
              );
            }}
          >
            <img alt='' src={require("../../imgs/tx.png")} />
            <p>提现</p>
          </div>
        </div>
        {/* 拼团 */}
        <div className='zuan_box'>
          <img alt='' src={require("../../imgs/pingtuan.png")} />
          <p>三人拼团</p>
          <span
            onClick={() => {
              this.props.history.push("/page/home/user/JoinAGrp");
            }}
          >
            立即拼团
          </span>

          {/* {this.state.level !== 3 ? (
            <span
              onClick={() => {
                this.props.history.push("/page/home/user/JoinAGrp");
              }}
            >
              立即拼团
            </span>
          ) : (
            <span
              onClick={() => {
                this.props.history.push("/page/home/user/vip");
              }}
            >
              年费会员
            </span>
          )} */}
        </div>

        {/* 年费 */}
        <div className='zuan_box'>
          <img alt='' src={require("../../imgs/zuan.png")} />
          <p>开通年费会员领免费课程</p>

          {this.state.level !== 3 ? (
            <span
              onClick={() => {
                this.props.history.push("/page/home/user/vip");
              }}
            >
              立即开通
            </span>
          ) : (
            <span
              onClick={() => {
                this.props.history.push("/page/home/user/vip");
              }}
            >
              年费会员
            </span>
          )}
        </div>

        {this.state.is_quan !== 2 ? (
          <div className='zuan_box1'>
            <img alt='' src={require("../../imgs/kapian.png")} />
            <p>体验卡</p>
            <span>
              倒计时:{this.state.day}天{this.state.hour}时{this.state.minute}分
              {this.state.second}秒
            </span>
          </div>
        ) : (
          <span></span>
        )}

        <h1 className='utitle'>我的服务</h1>
        <div className='user_list'>
          <div
            className='item'
            onClick={() => {
              this.props.history.push("/page/home/user/orderlist");
            }}
          >
            <img
              alt=''
              src={require("../../imgs/uicon1.png")}
              className='icon'
            />
            <p>全部订单</p>
            {/* <img alt='' src={require('../../imgs/r1.png')} className='r1' /> */}
          </div>
          <div
            className='item'
            onClick={() => {
              this.props.history.push("/page/home/user/team");
            }}
          >
            <img
              alt=''
              src={require("../../imgs/uicon2.png")}
              className='icon'
            />
            <p>我的团队</p>
            {/* <img alt='' src={require('../../imgs/r1.png')} className='r1' /> */}
          </div>
          <div
            className='item'
            onClick={() => {
              this.props.history.push("/page/home/user/activity");
            }}
          >
            <img
              alt=''
              src={require("../../imgs/uicon3.png")}
              className='icon'
            />
            <p>我的活动</p>
            {/* <img alt='' src={require('../../imgs/r1.png')} className='r1' /> */}
          </div>
          <div
            className='item'
            onClick={() => {
              this.props.history.push("/page/home/user/medal");
            }}
          >
            <img
              alt=''
              src={require("../../imgs/uicon4.png")}
              className='icon'
            />
            <p>学习勋章</p>
            {/* <img alt='' src={require('../../imgs/r1.png')} className='r1' /> */}
          </div>
          <div
            className='item'
            onClick={() => {
              this.props.history.push("/page/home/user/share");
            }}
          >
            <img alt='' src={require("../../imgs/yaoq.png")} className='icon' />
            <p>邀请好友</p>
            {/* <img alt='' src={require('../../imgs/r1.png')} className='r1' /> */}
          </div>
          {/* 水晶 */}
          <div
            className='item'
            onClick={() => {
              this.props.history.push("/page/home/user/crystalExchange");
            }}
          >
            <img alt='' src={require("../../imgs/11.png")} className='icon' />
            <p>水晶兑换</p>
            {/* <img alt='' src={require('../../imgs/r1.png')} className='r1' /> */}
          </div>
        </div>
        <h1 className='utitle'>每日任务</h1>
        <div className='renw_list'>
          <div className='item'>
            <img alt='' src={require("../../imgs/rw1.png")} />
            <div>
              <p>每日签到</p>
              <span>可获得{this.state.sign_num}朵小红花</span>
            </div>
            {this.state.sign === 0 ? (
              <p className='wei' onClick={this.sign.bind(this)}>
                签到
              </p>
            ) : (
              <p className='yi'>已完成</p>
            )}
          </div>
          <div className='item'>
            <img alt='' src={require("../../imgs/rw2.png")} />
            <div>
              <p>广场点赞</p>
              <span>每日广场前5次可获得{this.state.dianzan_num}朵小红花</span>
            </div>
            {this.state.dianzan < 5 ? (
              <p className='wei'>{this.state.dianzan}/5</p>
            ) : (
              <p className='yi'>已完成</p>
            )}
          </div>
          <div className='item'>
            <img alt='' src={require("../../imgs/rw3.png")} />
            <div>
              <p>邀请好友</p>
              <span>邀请好友注册成功可获得{this.state.invite}朵小红花</span>
            </div>
            {this.state.share === 0 ? (
              <p
                className='wei'
                onClick={() => {
                  this.props.history.push("/page/home/user/share");
                }}
              >
                去分享
              </p>
            ) : (
              <p className='yi'>已完成</p>
            )}
          </div>
        </div>
      </div>
    );
  }
}
